import {
  END_ANIMATION,
  END_RECORD,
  HIDDEN_MODAL,
  HIDE_LOADING,
  PLAY_NEXT,
  RESET_CURRENT,
  SAVE_RECORD,
  SAVE_VIDEO_CONTEXT,
  SET_CURRENT_PLAY_STATE,
  SET_VOICE_PATH,
  SHOW_LOADING,
  SHOW_MODAL,
  SHOW_NEXT_BEANS,
  SHOW_POST,
  START_ANIMATION,
  START_RECORD,
  UPDATE_CURRENT_TIME
} from "../../mutation-types";
import { Toast } from "../../../utils/modal";
import FLIP from "../../../utils/flip";
import { upload } from "../../../utils/uploadFile";
import { RedirectTo } from "../../../utils/router";
import { soundList } from "../../../api/url.config";

export const showLoading = ({ commit }) => {
  console.log("展示全局Loading");
  commit(SHOW_LOADING, true);
};

export const hideLoading = ({ commit }) => {
  console.log("隐藏全局Loading");
  commit(HIDE_LOADING, false);
};

export const hiddenModal = ({ commit }) => {
  commit(HIDDEN_MODAL);
};

export const showModal = ({ commit }) => {
  commit(SHOW_MODAL);
};

export const startAnimation = async (
  { commit, state, dispatch },
  { current, target }
) => {
  console.log(current, target);
  try {
    const flip = new FLIP(".bean-" + (current + 1), ".b-start", target);
    let animation = await flip.animation();
    commit(START_ANIMATION, {
      animationShow: true,
      isAnimationEnd: false,
      animation
    });
    let animationScale = await flip.animationScale();
    setTimeout(() => {
      commit(END_ANIMATION, {
        animationShow: true,
        isAnimationEnd: true,
        animation: animationScale
      });
      dispatch("playBeanVoice", { voicePath: soundList.bean });
    }, 2000);
    let animationEnd = await flip.animationEnd();
    setTimeout(() => {
      commit(END_ANIMATION, {
        animationShow: false,
        isAnimationEnd: true,
        animation: animationEnd
      });
    }, 3000);
  } catch (e) {
    console.log(e);
  }
};

// 播放录音
let innerAudioContext = uni.createInnerAudioContext(); // 获取实例
innerAudioContext.obeyMuteSwitch = false; // 是否遵循系统静音开关，当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音，默认值 true

// 录音
const recorderManager = uni.getRecorderManager();

// 开始录音
export const startRecord = async ({ commit, dispatch }) => {
  try {
    innerAudioContext.stop();
    dispatch("setCurrentPlayState", {
      currentPlayState: "",
      currentRecordIsFinish: true
    });

    recorderManager.start({
      format: "mp3"
    });
    commit(START_RECORD);
    recorderManager._recordTime = new Date();
  } catch (e) {
    console.log(e);
  }
};

// 结束录音
export const endRecord = async ({ commit }) => {
  try {
    recorderManager.onStop(res => {
      console.log(res);
      if (!res) {
        return;
      }
      const {
        tempFilePath,
        duration = new Date() - recorderManager._recordTime
      } = res;
      commit(END_RECORD);
      console.log(duration);
      if (duration < 2000) {
        return Toast({ title: "录音时长少于2秒，请重新录音" });
      }
      commit(SAVE_RECORD, { recordPath: tempFilePath });
    });
    recorderManager.stop();
  } catch (e) {
    console.log(e);
  }
};

// 停止录音
export const stopRecord = () => {
  recorderManager.stop();
};

// 设置声音路径
export const setVoicePath = ({ commit }, { voicePath }) => {
  console.log("currentVoicePath:" + voicePath);
  commit(SET_VOICE_PATH, voicePath);
};

// 设置当前声音播放状态
export const setCurrentPlayState = (
  { commit },
  { currentPlayState, currentRecordIsFinish }
) => {
  commit(SET_CURRENT_PLAY_STATE, { currentPlayState, currentRecordIsFinish });
};

// 重置播放状态
export const resetState = ({ dispatch }) => {
  // 当播放出错
  innerAudioContext.onError(() => {
    console.log("绑定错误结束事件");
    innerAudioContext.offPlay();
    dispatch("setCurrentPlayState", {
      currentPlayState: "",
      currentRecordIsFinish: true
    });
    innerAudioContext.offError();
  });

  // 当播放结束
  innerAudioContext.onEnded(() => {
    console.log("绑定自然结束事件");
    innerAudioContext.offPlay();
    dispatch("setCurrentPlayState", {
      currentPlayState: "",
      currentRecordIsFinish: true
    });
    innerAudioContext.offEnded();
  });
};

// 播放录音
export const playVoice = ({ dispatch, state, commit }) => {
  innerAudioContext.stop();

  const { currentVoicePath } = state;
  if (!currentVoicePath) {
    return;
  }
  dispatch("resetState");
  innerAudioContext.onCanplay(() => {
    console.log(innerAudioContext.duration);
  });

  innerAudioContext.src = currentVoicePath;
  innerAudioContext.play();
  innerAudioContext.onTimeUpdate(() => {
    // console.log(UPDATE_CURRENT_TIME, innerAudioContext.currentTime);
  });
};

// 暂停播放
export const _pause = ({ state }) => {
  if (state.currentPlayState) {
    innerAudioContext.pause();
  }
};

// 继续播放
export const _continuePlaying = ({ state }) => {
  if (state.currentPlayState) {
    innerAudioContext.play();
  }
};

// 播放导读页面录音
export const playLoadingPageVoice = ({ dispatch, commit }, { voicePath }) => {
  innerAudioContext.onPlay(e => {
    console.log("播放导读页录音");
    dispatch("setCurrentPlayState", {
      currentPlayState: "guide",
      currentRecordIsFinish: false
    });
  });

  innerAudioContext.onEnded(() =>
    dispatch("setCurrentPlayState", {
      currentPlayState: "guide",
      currentRecordIsFinish: true
    })
  );

  commit(RESET_CURRENT);
  dispatch("setVoicePath", { voicePath });
  dispatch("playVoice");
};

// 播放金豆音
export const playBeanVoice = ({ dispatch, commit }, { voicePath }) => {
  innerAudioContext.onPlay(e => {
    console.log("播放金豆音");
    dispatch("setCurrentPlayState", {
      currentPlayState: "bean",
      currentRecordIsFinish: false
    });
  });

  dispatch("setVoicePath", { voicePath });
  dispatch("playVoice");
};

// 播放课程完成音
export const playCourseFinishVoice = ({ dispatch, commit }, { voicePath }) => {
  innerAudioContext.onPlay(e => {
    console.log("播放课程完成音");
    dispatch("setCurrentPlayState", {
      currentPlayState: "courseFinish",
      currentRecordIsFinish: false
    });
  });

  dispatch("setVoicePath", { voicePath });
  dispatch("playVoice");
};

// 答题错误音效
export const playErrorVoice = ({ dispatch, commit }, { voicePath }) => {
  innerAudioContext.onPlay(e => {
    console.log("答题错误音效");
    dispatch("setCurrentPlayState", {
      currentPlayState: "error",
      currentRecordIsFinish: false
    });
  });
  dispatch("setVoicePath", { voicePath });
  dispatch("playVoice");
};

// 循环计时
export const interval = ({ commit, state, dispatch }) => {
  let a = setTimeout(() => {
    if (["courseFinish", "error", "bean"].includes(state.currentPlayState)) {
      return commit(UPDATE_CURRENT_TIME, 0);
    }
    if (state.currentPlayState === "") {
      return clearTimeout(a);
    }
    commit(UPDATE_CURRENT_TIME, Math.ceil(innerAudioContext.currentTime));
    dispatch("interval");
  }, 30);
};

// 播放正文
export const playContentPageVoice = (
  { dispatch, state, rootState, commit },
  { isAutoPlay } = { isAutoPlay: true }
) => {
  const { current, recordPath } = state;
  const { lessonDetail } = rootState.Course;
  const { audio, upload_audio } = lessonDetail.info[current] || {
    upload_audio: ""
  };

  if (isAutoPlay) {
    // 如果是自动播放 `第三方录音` ，并且之前意境录过音
    dispatch("hideLoading");
    if (upload_audio) {
      return commit(SAVE_RECORD, { upload_audio });
    }
  }

  dispatch("setCurrentPlayState", {
    currentPlayState: "record",
    currentRecordIsFinish: false
  });

  innerAudioContext.onPlay(() => {
    console.log("播放正文");
    dispatch("hideLoading");
    dispatch("interval");
    commit(SAVE_RECORD, { upload_audio: recordPath });
    dispatch("setCurrentPlayState", {
      currentPlayState: "record",
      currentRecordIsFinish: false
    });
  });

  innerAudioContext.onEnded(() => {
    console.log("绑定自然结束事件");
    innerAudioContext.offPlay();
    dispatch("setCurrentPlayState", {
      currentPlayState: "",
      currentRecordIsFinish: true
    });
    innerAudioContext.offEnded();
  });

  dispatch("setVoicePath", { voicePath: audio });
  dispatch("playVoice");
};

// 播放自录音
export const playRecordVoice = ({ dispatch, state }) => {
  const { recordPath, upload_audio } = state;
  innerAudioContext.onPlay(e => {
    console.log("播放自录音");
    dispatch("setCurrentPlayState", {
      currentPlayState: "voice",
      currentRecordIsFinish: false
    });
  });
  dispatch("resetState", {});
  dispatch("setVoicePath", { voicePath: recordPath || upload_audio });
  dispatch("playVoice");
};

export const playNextVoice = async (
  { commit, dispatch, state, rootState },
  { target, count }
) => {
  try {
    const { current, recordPath, isAnimationEnd } = state;
    const { lessonDetail, id, type_id } = rootState.Course;
    const { upload_audio } = lessonDetail.info[current] || {
      upload_audio: ""
    };

    // 如果 读一读 和 学以致用需要上传录音
    if ([2, 4].includes(parseInt(type_id))) {
      if (!(upload_audio || recordPath)) {
        return Toast({ title: "请重新录音" });
      }
      dispatch("startAnimation", { current: (current + 1) * 2 - 1, target });
      if (recordPath) {
        const { data: recording } = await upload({
          filePath: recordPath
        });
        commit(SAVE_RECORD, { recordPath: "" });
        await dispatch(
          "Course/reqCompleteTask",
          {
            id: lessonDetail.info[current].id,
            type_id,
            recording
          },
          { root: true }
        );
      }
    }

    // 练一练 只播放录音即可
    setTimeout(() => {
      if (current + 1 >= lessonDetail.info.length) {
        commit(SHOW_NEXT_BEANS, { current_beans: current + 1 });
        setTimeout(() => {
          RedirectTo({
            url: "/pages_course/course_finish/course_finish",
            query: { id, type_id, count }
          });
        }, 500);
        return;
      }

      commit(PLAY_NEXT, { current: current + 1 });
      commit(SHOW_NEXT_BEANS, { current_beans: current + 1 });

      if ([2, 3].includes(parseInt(type_id))) {
        dispatch("playContentPageVoice");
      }

      // 学以致用
      if (parseInt(type_id) === 4) {
        const { videoContext } = state;
        dispatch("playVideo", { videoContext });
      }
    }, 3000);
  } catch (e) {
    console.log(e);
  }
};

// 停止播放
export const stopPlay = ({ dispatch, commit }) => {
  commit(RESET_CURRENT);
  innerAudioContext.src = "";
  innerAudioContext.onStop(() => {
    dispatch("setCurrentPlayState", {
      currentPlayState: "",
      currentRecordIsFinish: false
    });
    dispatch("setVoicePath", { voicePath: "" });
    innerAudioContext.offStop();
  });
  innerAudioContext.stop();
};

export const playVideo = (
  { commit, dispatch, state, rootState },
  { videoContext, isAutoPlay = true }
) => {
  const { current } = state;
  const { lessonDetail } = rootState.Course;
  const { upload_audio } = lessonDetail.info[current] || {
    upload_audio: ""
  };
  if (isAutoPlay) {
    // 如果是自动播放 `第三方录音` ，并且之前意境录过音
    if (upload_audio) {
      dispatch("hideLoading");

      return commit(SAVE_RECORD, { upload_audio });
    }
  }
  setTimeout(()=>{
    videoContext.play();
  },3000);

  let _a = 1;
  const a = setInterval(()=>{
    if (++_a > 30) {
      clearInterval(a)
    }
    dispatch("setCurrentPlayState", {
      currentPlayState: "video",
      currentRecordIsFinish: false
    });
  },100)

};

export const saveVideoContext = ({ commit }, { videoContext }) => {
  commit(SAVE_VIDEO_CONTEXT, { videoContext });
};

export const videoPlay = ({ dispatch, state, rootState, commit }) => {
  const { current } = state;
  const { lessonDetail } = rootState.Course;
  const { upload_audio } = lessonDetail.info[current];
  commit(SAVE_RECORD, { upload_audio });
  dispatch("setCurrentPlayState", {
    currentPlayState: "video",
    currentRecordIsFinish: false
  });
  dispatch(HIDE_POST);
  setTimeout(()=>{
    dispatch(SHOW_POST)
  },3000);
  dispatch("hideLoading");
};

export const videoEnded = ({ dispatch }) => {
  dispatch("hideLoading");

  dispatch("setCurrentPlayState", {
    currentPlayState: "",
    currentRecordIsFinish: true
  });
};
